package _28define.udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UserAnother {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket=new DatagramSocket(8888);

        new Thread(new Sender2(9999,"192.168.106.130",datagramSocket)).start();
        new Thread(new Reserve2(datagramSocket)).start();
    }
}
class Sender2 implements Runnable{
    int port;
    String ip;
    DatagramSocket datagramSocket;

    public Sender2(int port, String ip ,DatagramSocket datagramSocket) {
        this.port = port;
        this.ip = ip;
        this.datagramSocket = datagramSocket;
    }
    @Override
    public void run() {
        Scanner sc=new Scanner(System.in);
        while (true){
             String s=sc.nextLine();
            try {
                InetAddress targetIP=InetAddress.getByName(ip);
                byte[] bytes=s.getBytes();
                DatagramPacket sendPacket=new DatagramPacket(bytes,0,bytes.length,targetIP,port);
                datagramSocket.send(sendPacket);
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
class Reserve2 implements Runnable{
    DatagramSocket datagramSocket;

    public Reserve2(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] bytes=new byte[1024];
                DatagramPacket receiverPacket=new DatagramPacket(bytes,0,bytes.length);
                datagramSocket.receive(receiverPacket);
                int length=receiverPacket.getLength();
                byte[] data=receiverPacket.getData();
                int offset= receiverPacket.getOffset();
                String msg=new String(data,offset,length);
                System.out.println("接收到了来自"+receiverPacket.getSocketAddress()+"的消息："+msg);
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}